const db = require('../config/database');
const logger = require('../config/logger');
const crypto = require('crypto');
const path = require('path');
const fs = require('fs');

/**
 * 创建文件分享
 */
exports.createShare = async (req, res) => {
  try {
    const { fileId, password, expiryHours } = req.body;
    const userId = req.user.id;

    // 检查文件是否存在且属于该用户
    const [files] = await db.query(
      'SELECT * FROM files WHERE id = ? AND user_id = ? AND is_deleted = 0',
      [fileId, userId]
    );

    if (files.length === 0) {
      return res.status(404).json({
        success: false,
        message: '文件不存在或无权限'
      });
    }

    const file = files[0];

    // 生成唯一分享码
    const shareCode = crypto.randomBytes(8).toString('hex');

    // 计算过期时间
    let expiryTime = null;
    if (expiryHours && expiryHours > 0) {
      expiryTime = new Date(Date.now() + expiryHours * 60 * 60 * 1000);
    }

    // 创建分享记录
    const [result] = await db.query(
      `INSERT INTO file_shares (file_id, user_id, share_code, password, expiry_time, created_at)
       VALUES (?, ?, ?, ?, ?, NOW())`,
      [fileId, userId, shareCode, password || null, expiryTime]
    );

    logger.info(`用户 ${userId} 创建文件分享: ${file.file_name}, 分享码: ${shareCode}`);

    res.json({
      success: true,
      message: '分享创建成功',
      data: {
        shareId: result.insertId,
        shareCode,
        shareUrl: `/share/${shareCode}`,
        expiryTime
      }
    });
  } catch (error) {
    logger.error('创建文件分享失败:', error);
    res.status(500).json({
      success: false,
      message: '创建分享失败'
    });
  }
};

/**
 * 获取分享信息（无需登录）
 */
exports.getShareInfo = async (req, res) => {
  try {
    const { code } = req.params;

    const [shares] = await db.query(
      `SELECT s.*, f.file_name, f.file_size, f.file_path, f.mime_type,
              u.username as owner_name
       FROM file_shares s
       JOIN files f ON s.file_id = f.id
       JOIN users u ON s.user_id = u.id
       WHERE s.share_code = ? AND s.is_deleted = 0 AND f.is_deleted = 0`,
      [code]
    );

    if (shares.length === 0) {
      return res.status(404).json({
        success: false,
        message: '分享不存在'
      });
    }

    const share = shares[0];

    // 检查是否过期
    if (share.expiry_time && new Date(share.expiry_time) < new Date()) {
      return res.status(410).json({
        success: false,
        message: '分享已过期'
      });
    }

    // 如果需要密码，不返回文件详细信息
    const requirePassword = !!share.password;

    res.json({
      success: true,
      data: {
        require_password: requirePassword,
        authenticated: !requirePassword,
        file: requirePassword ? null : {
          name: share.file_name,
          size: share.file_size,
          type: getFileType(share.mime_type),
          created_at: share.created_at,
          expiry_time: share.expiry_time,
          download_count: share.download_count
        }
      }
    });
  } catch (error) {
    logger.error('获取分享信息失败:', error);
    res.status(500).json({
      success: false,
      message: '获取分享信息失败'
    });
  }
};

/**
 * 验证分享密码（无需登录）
 */
exports.verifyPassword = async (req, res) => {
  try {
    const { code } = req.params;
    const { password } = req.body;

    const [shares] = await db.query(
      `SELECT s.*, f.file_name, f.file_size, f.file_path, f.mime_type
       FROM file_shares s
       JOIN files f ON s.file_id = f.id
       WHERE s.share_code = ? AND s.is_deleted = 0`,
      [code]
    );

    if (shares.length === 0) {
      return res.status(404).json({
        success: false,
        message: '分享不存在'
      });
    }

    const share = shares[0];

    // 检查是否过期
    if (share.expiry_time && new Date(share.expiry_time) < new Date()) {
      return res.status(410).json({
        success: false,
        message: '分享已过期'
      });
    }

    // 验证密码
    if (share.password !== password) {
      return res.status(401).json({
        success: false,
        message: '密码错误'
      });
    }

    res.json({
      success: true,
      message: '验证成功',
      data: {
        file: {
          name: share.file_name,
          size: share.file_size,
          type: getFileType(share.mime_type),
          created_at: share.created_at,
          expiry_time: share.expiry_time,
          download_count: share.download_count
        }
      }
    });
  } catch (error) {
    logger.error('验证密码失败:', error);
    res.status(500).json({
      success: false,
      message: '验证失败'
    });
  }
};

/**
 * 下载分享文件（无需登录）
 */
exports.downloadShare = async (req, res) => {
  try {
    const { code } = req.params;

    const [shares] = await db.query(
      `SELECT s.*, f.file_name, f.file_path
       FROM file_shares s
       JOIN files f ON s.file_id = f.id
       WHERE s.share_code = ? AND s.is_deleted = 0`,
      [code]
    );

    if (shares.length === 0) {
      return res.status(404).json({
        success: false,
        message: '分享不存在'
      });
    }

    const share = shares[0];

    // 检查是否过期
    if (share.expiry_time && new Date(share.expiry_time) < new Date()) {
      return res.status(410).json({
        success: false,
        message: '分享已过期'
      });
    }

    const filePath = path.join(__dirname, '../../', share.file_path);

    // 检查文件是否存在
    if (!fs.existsSync(filePath)) {
      return res.status(404).json({
        success: false,
        message: '文件不存在'
      });
    }

    // 更新下载次数
    await db.query(
      'UPDATE file_shares SET download_count = download_count + 1 WHERE id = ?',
      [share.id]
    );

    logger.info(`分享文件下载: ${share.file_name}, 分享码: ${code}`);

    // 发送文件
    res.download(filePath, share.file_name);
  } catch (error) {
    logger.error('下载分享文件失败:', error);
    res.status(500).json({
      success: false,
      message: '下载失败'
    });
  }
};

/**
 * 获取用户的分享列表
 */
exports.getUserShares = async (req, res) => {
  try {
    const userId = req.user.id;
    const { page = 1, limit = 20 } = req.query;
    const offset = (page - 1) * limit;

    const [shares] = await db.query(
      `SELECT s.*, f.file_name, f.file_size, f.mime_type
       FROM file_shares s
       JOIN files f ON s.file_id = f.id
       WHERE s.user_id = ? AND s.is_deleted = 0
       ORDER BY s.created_at DESC
       LIMIT ? OFFSET ?`,
      [userId, parseInt(limit), offset]
    );

    const [countResult] = await db.query(
      'SELECT COUNT(*) as total FROM file_shares WHERE user_id = ? AND is_deleted = 0',
      [userId]
    );

    res.json({
      success: true,
      data: {
        shares,
        total: countResult[0].total,
        page: parseInt(page),
        limit: parseInt(limit)
      }
    });
  } catch (error) {
    logger.error('获取分享列表失败:', error);
    res.status(500).json({
      success: false,
      message: '获取分享列表失败'
    });
  }
};

/**
 * 取消分享
 */
exports.cancelShare = async (req, res) => {
  try {
    const { id } = req.params;
    const userId = req.user.id;

    // 检查分享是否存在且属于该用户
    const [shares] = await db.query(
      'SELECT * FROM file_shares WHERE id = ? AND user_id = ?',
      [id, userId]
    );

    if (shares.length === 0) {
      return res.status(404).json({
        success: false,
        message: '分享不存在或无权限'
      });
    }

    // 软删除
    await db.query(
      'UPDATE file_shares SET is_deleted = 1 WHERE id = ?',
      [id]
    );

    logger.info(`用户 ${userId} 取消分享: ${id}`);

    res.json({
      success: true,
      message: '分享已取消'
    });
  } catch (error) {
    logger.error('取消分享失败:', error);
    res.status(500).json({
      success: false,
      message: '取消分享失败'
    });
  }
};

// 辅助函数：根据MIME类型获取文件类型
function getFileType(mimeType) {
  if (!mimeType) return 'file';
  
  if (mimeType.startsWith('image/')) return 'image';
  if (mimeType.startsWith('video/')) return 'video';
  if (mimeType.startsWith('audio/')) return 'audio';
  if (mimeType.includes('pdf') || mimeType.includes('document') || mimeType.includes('text')) return 'document';
  if (mimeType.includes('zip') || mimeType.includes('rar') || mimeType.includes('7z')) return 'archive';
  
  return 'file';
}

